package org.fhm.zdte.common.service.transmission;

import org.fhm.substrate.annotation.Component;
import org.fhm.zdte.common.constant.protocol.PacketType;
import org.fhm.zdte.common.constant.protocol.ResponseMessageType;
import org.fhm.zdte.common.protocol.AbstractMessageMonitor;
import org.fhm.zdte.common.protocol.AbstractMessageStandard;

import java.util.Objects;

/**
 * A common message monitor.
 *
 * @author 谭波
 * @since 2023/11/4
 */
@Component
public class CommonMessageMonitor extends AbstractMessageMonitor {

    @Override
    public boolean isLawful(AbstractMessageStandard messageStandard) {
        if (Objects.isNull(messageStandard)) {
            return false;
        }
        return PacketType.isPacketType(messageStandard.getPacketType())
                || ResponseMessageType.isResponseMessageType(messageStandard.getResponseMessageType());
    }

    @Override
    public boolean isSubAckMessage(AbstractMessageStandard messageStandard) {
        if (Objects.isNull(messageStandard)) {
            return false;
        }
        ResponseMessageType type;
        return isIllegalUserGroupMessage(messageStandard)
                && Objects.nonNull((type = messageStandard.getResponseMessageType()))
                && type.equals(ResponseMessageType.MESSAGE_ACK);
    }

    @Override
    public boolean isSubMessage(AbstractMessageStandard messageStandard) {
        if (Objects.isNull(messageStandard)) {
            return false;
        }
        return isIllegalUserGroupMessage(messageStandard)
                && Objects.isNull(messageStandard.getResponseMessageType());
    }

    @Override
    public boolean isFailMessage(AbstractMessageStandard message) {
        ResponseMessageType type;
        return Objects.nonNull((type = message.getResponseMessageType()))
                && ResponseMessageType.isFailResponseMessageType(type);
    }

    @Override
    public boolean isSuccessful(AbstractMessageStandard message) {
        ResponseMessageType type;
        return Objects.nonNull((type = message.getResponseMessageType()))
                && type.equals(ResponseMessageType.MESSAGE_SUCCESS);
    }

    @Override
    public boolean isAck(AbstractMessageStandard message) {
        ResponseMessageType type;
        return Objects.nonNull((type = message.getResponseMessageType()))
                && type.equals(ResponseMessageType.MESSAGE_ACK);
    }

    private boolean isIllegalUserGroupMessage(AbstractMessageStandard message) {
        return Objects.nonNull(message.getMessageNumber())
                &&
                Objects.nonNull(message.getSerialNumber())
                &&
                Objects.nonNull(message.getMessageLength());
    }

}
